package com.wnxy.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wnxy.entity.Employee;
import com.wnxy.mapper.EmployeeMapper;
import com.wnxy.service.EmployeeService;
import com.wnxy.util.DBUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class EmployeeServiceImpl implements EmployeeService {

    @Override
    public List<Employee> findAllemp() {
        SqlSession sqlSession = DBUtil.openSqlSession(true);
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        List<Employee> list = mapper.findAll();
        sqlSession.close();
        return list.isEmpty()?null:list;
    }

    @Override
    public PageInfo<Employee> findOnePage(int currentPage, Employee esi) {
        SqlSession sqlSession = DBUtil.openSqlSession(true);
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        // 使用分页插件
        PageHelper.startPage(currentPage, 5);
        List<Employee> list = mapper.findByCondition(esi);
        PageInfo<Employee> info = null;
        if(list != null){
            info = new PageInfo<>(list);
        }
        sqlSession.close();
        return info;
    }

    @Override
    public boolean deleteById(Integer id) {
        if (id==null||id==0){
            return false;
        }
        SqlSession sqlSession = DBUtil.openSqlSession(true);
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        int row = mapper.deleteById(id);
        sqlSession.close();
        return row>0;
    }

    @Override
    public boolean addEmp(Employee employee) {
        if (employee==null){
            return false;
        }
        SqlSession sqlSession = DBUtil.openSqlSession(true);
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        int row = mapper.add(employee);
        sqlSession.close();
        return row>0;
    }

    @Override
    public boolean updateEmp(Employee emp) {
        if (emp==null){
            return false;
        }
        SqlSession sqlSession = DBUtil.openSqlSession(true);
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        int row = mapper.updateByCondition(emp);

        sqlSession.close();
        return row>0;
    }

    @Override
    public boolean updateImg(Integer id,String image) {
        if (image==null||id==0){
            return false;
        }
        SqlSession sqlSession = DBUtil.openSqlSession(true);
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        Employee emp = new Employee();
        emp.setId(id);
        emp.setImage(image);
        int row = mapper.updateByCondition(emp);
        sqlSession.close();
        return row>0;
    }
}
